<template>
	<div>
		<div class="layout-padding w40" style="padding-right: 0px !important">
			<div class="layout-padding-auto layout-padding-view">
				<el-row class="ml10" v-show="showSearch">
					<el-form :inline="true" :model="queryFormData" ref="queryRef">
						<el-row :gutter="24" style="width: 100%">
							<el-col :span="12">
								<el-form-item label="检测时间">
									<el-date-picker
										v-model="queryFormData.detectionTime"
										type="daterange"
										start-placeholder="开始时间"
										end-placeholder="结束时间"
										format="YYYY-MM-DD"
										date-format="YYYY/MM/DD"
										:value-format="dateStr"
										:disabled-date="disabledDate"
									/>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="血糖高于正常值" style="width: 100%">
									<el-select v-model="queryFormData.labeling">
										<el-option v-for="(item, index) in faselist" :key="index" :label="item.label" :value="item.value"></el-option>
									</el-select>
								</el-form-item>
							</el-col>

							<el-col :span="12">
								<!--                <el-form-item label="地区" style="width: 100%;">-->
								<!--                  <el-select v-model="queryFormData.labeling">-->
								<!--                    <el-option v-for="(item, index) in faselist" :key="index" :label="item.label"-->
								<!--                               :value="item.value"></el-option>-->
								<!--                  </el-select>-->
								<!--                </el-form-item>-->

								<el-form-item label="地区" style="width: 100%">
									<el-select v-model="queryFormData.village">
										<el-option v-for="(item, index) in villageList" :key="index" :label="item.label" :value="item.value"></el-option>
									</el-select>
								</el-form-item>
							</el-col>

							<el-col :span="12">
								<el-form-item label="操作人" style="width: 100%">
									<el-select v-model="queryFormData.boarderName">
										<el-option v-for="(item, index) in boarderNameList" :key="index" :label="item" :value="item"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>

						<el-form-item>
							<el-button @click="queryBtn" formDialogRef icon="search" type="primary">
								{{ $t('common.queryBtn') }}
							</el-button>
							<el-button @click="handleOpenSearchPatient" type="primary" icon="EditPen">补录</el-button>
							<el-button @click="resetQuery" formDialogRef icon="Refresh">{{ $t('common.resetBtn') }}</el-button>
						</el-form-item>
					</el-form>
				</el-row>

				<el-row>
					<div class="mb8" style="width: 100%">
						<!--          <el-button icon="folder-add" type="primary" class="ml10" @click="formDialogRef.openDialog()"-->
						<!--            v-auth="'blood_bloodxCustomerBlood_add'">-->
						<!--            新 增-->
						<!--          </el-button>-->
						<el-button plain icon="Delete" type="primary" @click="handleDelete(selectIds)"> 删除 </el-button>
						<right-toolbar
							v-model:showSearch="showSearch"
							:export="'blood_bloodxCustomerBlood_export'"
							@exportExcel="exportExcel"
							class="ml10 mr20"
							style="float: right"
							@queryTable="getDataList"
						></right-toolbar>
					</div>
				</el-row>
				<el-table
					size="small"
					:data="state.dataList"
					v-loading="state.loading"
					border
					:cell-style="tableStyle.cellStyle"
					:header-cell-style="tableStyle.headerCellStyle"
					@selection-change="selectionChangHandle"
					@sort-change="sortChangeHandle"
				>
					<el-table-column type="selection" width="40" align="center" />
					<el-table-column type="index" label="#" width="45" />
					<el-table-column prop="detectionTime" label="检测时间" width="150" show-overflow-tooltip>
						<!--						<template #default="scope">-->
						<!--							{{ scope.row.detectionTime?.substring(0, 10) }}-->
						<!--						</template>-->
					</el-table-column>
					<el-table-column prop="boarderName" label="操作人" show-overflow-tooltip />
					<el-table-column prop="name" label="姓名" show-overflow-tooltip />
					<el-table-column prop="isFasting" label="空腹状态" show-overflow-tooltip>
						<template #default="scope">
							<dict-tag :options="bloodx_fasting" :value="scope.row.isFasting"></dict-tag>
						</template>
					</el-table-column>
					<el-table-column prop="number" label="血糖值" show-overflow-tooltip />
					<el-table-column prop="icCard" label="身份证号" show-overflow-tooltip />
					<el-table-column prop="medicalCard" label="社保卡号" show-overflow-tooltip />
					<!--        <el-table-column label="操作" width="150">-->
					<!--          <template #default="scope">-->
					<!--            <el-button icon="edit-pen" text type="primary" v-auth="'blood_bloodxCustomerBlood_edit'"-->
					<!--              @click="formDialogRef.openDialog(scope.row.id)">编辑</el-button>-->
					<!--            <el-button icon="delete" text type="primary" v-auth="'blood_bloodxCustomerBlood_del'" @click="handleDelete([scope.row.id])">删除</el-button>-->
					<!--          </template>-->
					<!--        </el-table-column>-->
				</el-table>
				<pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" v-bind="state.pagination" />
			</div>

			<!-- 编辑、新增  -->
			<form-dialog ref="formDialogRef" @refresh="getDataList" />
		</div>

		<div class="layout-padding w60" style="left: 40%">
			<!--      <div class="layout-padding-auto layout-padding-view">-->

			<el-card class="relative h-full">
				<el-row class="ml10" v-show="showSearch">
					<el-form :inline="true" :model="echartForm" ref="queryRef" style="width: 100%">
						<el-row :gutter="24" style="width: 100%">
							<el-col :span="12">
								<el-form-item label="检测时间">
									<el-date-picker
										v-model="echartForm.time"
										type="daterange"
										start-placeholder="开始时间"
										end-placeholder="结束时间"
										format="YYYY-MM-DD"
										date-format="YYYY/MM/DD"
										:value-format="dateStr"
									/>
								</el-form-item>
							</el-col>
							<!-- <el-form-item label="是否院内">
							<el-select v-model="queryFormData.appoint" multiple style="width: 100%">
								<el-option v-for="(item, index) in isIn" :key="index" :label="item.label" :value="item.value"></el-option>
							</el-select>
						</el-form-item> -->
							<el-col :span="6">
								<el-form-item label="是否空腹" style="width: 100%">
									<el-select v-model="echartForm.isFasting">
										<el-option v-for="(item, index) in fastList" :key="index" :label="item.label" :value="item.value"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="6">
								<el-form-item label="地区" style="width: 100%">
									<el-select v-model="echartForm.village">
										<el-option v-for="(item, index) in villageList" :key="index" :label="item.label" :value="item.value"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
						<el-form-item>
							<el-button @click="getAvgValueMap" icon="search" type="primary">
								{{ $t('common.queryBtn') }}
							</el-button>
							<el-button @click="rest" icon="Refresh"> 重置 </el-button>
							<!-- <el-button @click="handleChange">切换</el-button> -->
						</el-form-item>
					</el-form>
				</el-row>

				<div ref="chart" style="height: calc(100vh - 250px)" v-if="isShow" class="w-full h-fill" />
			</el-card>
			<!--      </div>-->
		</div>
		<SearchPatient ref="searchPatientRef" @add-success="getDataList" />
	</div>
</template>

<script setup lang="ts" name="systemBloodxCustomerBlood">
import { BasicTableProps, useTable } from '/@/hooks/table';
import { fetchList, delObjs, getAvgValue, getBoarderName } from '/@/api/blood/bloodxCustomerBlood';
import { sysVillageList } from '/@/api/blood/bloodxCustomer';
import { useMessage, useMessageBox } from '/@/hooks/message';
import { useDict } from '/@/hooks/dict';
import * as echarts from 'echarts';
import { formatDate } from '/@/utils/formatTime';
import { max } from 'lodash';
import SearchPatient from './components/search_patient.vue';
// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));
// 定义查询字典

const { bloodx_fasting } = useDict('bloodx_fasting');
// 定义变量内容
const formDialogRef = ref();
const echartForm = ref({
	time: [],
	isFasting: null,
	village: null,
	tag: 1,
	icCards: null,
});
// 搜索变量
const queryRef = ref();
const showSearch = ref(true);
// 多选变量
const selectObjs = ref([]) as any;
const isShow = ref(true);
const multiple = ref(true);
const queryFormData = reactive({
	detectionTime: [],
	labeling: '',
	village: '',
	boarderName: '',
});
const villageList = ref([
	{
		value: '',
		label: '全部',
	},
]);

const boarderNameList = ref([]);
const fastList = ref([
	{
		value: '',
		label: '全部',
	},
	{
		value: 1,
		label: '是',
	},
	{
		value: 0,
		label: '否',
	},
	{
		value: 2,
		label: '随机血糖',
	},
]);
const faselist = ref([
	{
		value: 1,
		label: '>7',
	},
	{
		value: 2,
		label: '>11',
	},
]);

const selectIds = ref([]);

const yearList = ref([0, 0, 0]);
const isInit = ref(false);
const bloodList = ref([0, 0, 0]);
const type = ref('bar');
const text = ref('普通血糖值');
const chart = ref(null);
onMounted(() => {
	getAvgValueMap();
	sysVillageList().then((res) => {
		if (res.data && res.data.length > 0) {
			const data = res.data.map((item) => {
				return {
					value: item.id,
					label: item.name,
				};
			});
			villageList.value = [...villageList.value, ...data];
		}
	});

	getBoarderName().then((res) => {
		boarderNameList.value = res.data;
	});
});

// 补录患者查询弹窗ref
const searchPatientRef = ref();
// 打开补录患者查询弹窗
function handleOpenSearchPatient() {
	searchPatientRef.value.openDialog();
}

const getAvgValueMap = () => {
	getAvgValue(
		Object.assign({
			startTime: echartForm.value.time[0] ? formatDate(new Date(echartForm.value.time[0]), 'YYYY-mm-dd HH:MM:SS') : '',
			endTime: echartForm.value.time[1] ? formatDate(new Date(echartForm.value.time[1]), 'YYYY-mm-dd HH:MM:SS') : '',
			village: echartForm.value.village >= 0 ? echartForm.value.village : null,
			isFasting: echartForm.value.isFasting >= 0 ? echartForm.value.isFasting : null,
			tag: echartForm.value.tag,
			icCards: echartForm.value.icCards,
		})
	).then((res) => {
		// 只保留年月日
		yearList.value = res.data.map((item: { day: string }) => item.day);
		bloodList.value = res.data.map((item: { blood: number }) => item.blood);
		console.log(yearList.value);
		const option = {
			title: {
				text: text.value,
			},
			tooltip: {
				trigger: 'axis',
				axisPointer: {
					type: 'shadow',
				},
			},
			grid: {
				// left: '10%',
				// right: '10%',
				bottom: '10%',
				// top: '10%',
				containLabel: true,
			},
			xAxis: {
				type: 'category',
				data: yearList.value,
				axisTick: {
					alignWithLabel: true,
				},
			},
			yAxis: {
				type: 'value',
				splitNumber: 5,
				max: 30,
			},
			series: [
				{
					data: bloodList.value,
					type: type.value,
					label: {
						show: true,
						position: 'top',
					},
					barWidth: '30%',
				},
			],
		};

		setTimeout(() => {
			if (isInit.value === false) {
				chart.value = echarts.init(chart.value);
			}

			chart.value.setOption(option);
			isInit.value = true;
		}, 1000);
	});
};

const rest = () => {
	echartForm.value.time = [];
	echartForm.value.isFasting = null;
	echartForm.value.village = null;
	getAvgValueMap();
};
const handleChange = () => {
	// echartForm.value.tag = echartForm.value.tag === 1 ? 2 : 1
	// type.value = type.value === 'line' ? 'bar' : 'line';
	// text.value = text.value === '普通血糖值' ? '体检数据血糖值' : '普通血糖值';
	getAvgValueMap();
	// const option = {
	// 	title: {
	// 		text: '近三年血糖走势图',
	// 	},
	// 	tooltip: {
	// 		trigger: 'axis',
	// 		axisPointer: {
	// 			type: 'shadow',
	// 		},
	// 	},
	// 	xAxis: {
	// 		type: 'category',
	// 		data: yearList.value,
	// 		axisTick: {
	// 			alignWithLabel: true,
	// 		},
	// 	},
	// 	yAxis: {
	// 		type: 'value',
	// 	},
	// 	series: [
	// 		{
	// 			data: bloodList.value,
	// 			type: type.value,
	// 			label: {
	// 				show: true,
	// 				position: 'top',
	// 			},
	// 			barWidth: '30%',
	// 		},
	// 	],
	// };

	// setTimeout(() => {
	// 	console.log(213);
	// 	chart.value.setOption(option);
	// }, 600);
};

const disabledDate = (time: Date) => {
	return time.getTime() > Date.now();
};

const state: BasicTableProps = reactive<BasicTableProps>({
	queryForm: {},
	pageList: fetchList,
	descs: ['detection_time'],
});

//  table hook
const { getDataList, currentChangeHandle, sizeChangeHandle, sortChangeHandle, downBlobFile, tableStyle } = useTable(state);

const queryBtn = () => {
	if (queryFormData.detectionTime.length > 0) {
		// 判断是否存在 00:00:00  或者 23:59:59，存在则不处理，不存在则添加
		if (queryFormData.detectionTime[0].indexOf('00:00:00') === -1) {
			state.queryForm.startTime = queryFormData.detectionTime[0] + ' 00:00:00';
		}
		if (queryFormData.detectionTime[1].indexOf('23:59:59') === -1) {
			state.queryForm.endTime = queryFormData.detectionTime[1] + ' 23:59:59';
		}
	}
	state.queryForm.labeling = queryFormData.labeling;
	state.queryForm.village = queryFormData.village;
	state.queryForm.boarderName = queryFormData.boarderName;
	getDataList();
};

// 清空搜索条件
const resetQuery = () => {
	// 清空搜索条件
	queryRef.value?.resetFields();
	// 清除detectionTime
	queryFormData.detectionTime = [];
	state.queryForm.startTime = null;
	state.queryForm.endTime = null;
	state.queryForm.labeling = null;
	queryFormData.labeling = '';
	state.queryForm.village = null;
	queryFormData.village = '';
	state.queryForm.boarderName = null;
	queryFormData.boarderName = '';
	// 清空多选
	selectObjs.value = [];
	getDataList();
};

// 导出excel
const exportExcel = () => {
	downBlobFile('/blood/bloodxCustomerBlood/export', Object.assign(state.queryForm, { ids: selectObjs }), 'bloodxCustomerBlood.xlsx');
};

// 多选事件
const selectionChangHandle = (e) => {
	// selectObjs.value = objs.map(({ id }) => id);
	// multiple.value = !objs.length;
	// console.log(multiple.value)
	selectObjs.value = e.map(({ icCard }) => icCard);
	selectIds.value = e.map(({ id }) => id);
	console.log(selectObjs.value);
	echartForm.value.icCards = [];
	selectObjs.value.forEach((item) => {
		echartForm.value.icCards.push(item);
	});

	getAvgValueMap();
};

// 删除操作
const handleDelete = async (ids: string[]) => {
	// try {
	// 	await useMessageBox().confirm('此操作将永久删除');
	// } catch {
	// 	return;
	// }

	try {
		await delObjs(ids);
		getDataList(false);
		useMessage().success('删除成功');
	} catch (err: any) {
		useMessage().error(err.msg);
	}
};
</script>

<style scoped lang="scss">
:deep(.el-card__body) {
	width: 100%;
	height: 100%;
}

.relative {
	.el-card__body {
		display: flex;

		.h-fill {
			flex: 1;
		}
	}
}
</style>
